﻿using System;
using System.Net;

namespace Kay.WebClientApplication
{
    /// <summary>
    /// Web 客户端高级版
    /// </summary>
    public class WebClientExpert : WebClient
    {
        /// <summary>
        /// 当前 Web 客户端使用的 Cookie
        /// </summary>
        public CookieContainer Cookie { get; }

        /// <summary>
        /// 初始化 Web 客户端
        /// </summary>
        public WebClientExpert() : this(new CookieContainer()) { }

        /// <summary>
        /// 初始化 Web 客户端
        /// </summary>
        /// <param name="cookie">使用 Cookie</param>
        public WebClientExpert(CookieContainer cookie)
        {
            Cookie = cookie;
        }

        /// <inheritdoc />
        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);

            if (Cookie == null)
                return request;

            if (!(request is HttpWebRequest)) return request;

            var httpRequest = request as HttpWebRequest;
            httpRequest.CookieContainer = Cookie;

            return request;
        }
    }
}
